/** *******************************************************************
 * FlexDatabaseManager
 * @author  Jonnie Spratley
 * @contact jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.flexdatabasemanager.commands.query
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.serialization.json.JSON;
	import com.jonniespratley.flexdatabasemanager.business.FlexDatabaseManagerDelegate;
	import com.jonniespratley.flexdatabasemanager.events.query.AnalyeQueryEvent;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class AnalyeQueryCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		public function execute( event:CairngormEvent ) : void
		{
			model.interactingWithServer = true;
		
			var evt:AnalyeQueryEvent = event as AnalyeQueryEvent;
			var delegate:FlexDatabaseManagerDelegate = new FlexDatabaseManagerDelegate( this );
				delegate.analyzeQuery( model.currentUser, evt.aQuery ); 

		}

		public function result( data:Object ) : void
		{
			model.interactingWithServer = false;
			
			var result:ResultEvent = data as ResultEvent;
			//todo: add result handler
			//model.queryAnalyzedCollection = FlexDatabaseManagerFactory.parseJSONResult( data.result );
			if ( result.result is String )
			{
				var rawData:String = String( result.result ); 
				var jsonArray:Array = ( JSON.decode( rawData ) as Array );
				model.queryAnalyzed = new AnalyzeVO( jsonArray[ 0 ] );				
			}
			
		}

		public function fault( fault:Object ):void
		{
			model.interactingWithServer = false;
			
			var faultEvt:FaultEvent = fault as FaultEvent;
			Alert.show(faultEvt.fault.toString(), "Error");
			trace(faultEvt.fault.faultString);
		}

	}
}